package zj.com.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zfdang.multiple_images_selector.SelectorSettings;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import zj.com.activities.DshDetailEditActivity;
import zj.com.activities.DshListActivity;
import zj.com.activities.LookImgActivity;
import zj.com.adapter.LookImgGridAdapter;
import zj.com.adapter.UploadImgGridAdapter;
import zj.com.app.ZjApplication;
import zj.com.model.JcxDB;
import zj.com.model.RecordDetail;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.util.SharedPreferencesUtil;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/4.
 * 待审核问题编辑
 */
public class DshDetailEditFragment extends Fragment {


    public Intent intent;

    public GridView uploadGridView,uploadGridView2;
    public List<String> list;
    public LookImgGridAdapter adapter,wtAdapter,zgAdapter;
    public static final int REQUEST_CODE = 732;

    public  static ArrayList<String> mResults = new ArrayList<>();

    public EditText des_et,zg_et,yj_et;
    public TextView tg_tv,jj_tv;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dsh_detail_edit, container, false);
        obtainData();
        initView(view);
        return view;
    }


    public void initView(View view){

        list = new ArrayList<>();
        des_et = (EditText) view.findViewById(R.id.des_et);
        zg_et = (EditText) view.findViewById(R.id.zg_et);
        yj_et = (EditText) view.findViewById(R.id.yj_et);


        tg_tv = (TextView) view.findViewById(R.id.tg_tv);
        tg_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                doRepair(0);
            }
        });
        jj_tv = (TextView) view.findViewById(R.id.jj_tv);
        jj_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doRepair(1);

            }
        });

        uploadGridView = (GridView) view.findViewById(R.id.uploadGridView);
        uploadGridView2 = (GridView) view.findViewById(R.id.uploadGridView2);
        wtAdapter = new LookImgGridAdapter(list,getActivity());
        uploadGridView.setAdapter(wtAdapter);
        zgAdapter = new LookImgGridAdapter(list,getActivity());
        uploadGridView2.setAdapter(zgAdapter);

        uploadGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getActivity(), LookImgActivity.class);
                intent.putExtra("imgs", (Serializable) riskList);
                intent.putExtra("position",position);
                startActivity(intent);
            }
        });
        uploadGridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), LookImgActivity.class);
                intent.putExtra("imgs", (Serializable) attachList);
                intent.putExtra("position",position);
                startActivity(intent);
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // get selected images from selector
        if(requestCode == REQUEST_CODE) {
            if(resultCode == getActivity().RESULT_OK) {
                mResults = data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);
                assert mResults != null;

                // show results in textview
                StringBuilder sb = new StringBuilder();
                sb.append(String.format("Totally %d images selected:", mResults.size())).append("\n");
                list.clear();
                for(String result : mResults) {
                    list.add(result);
                    sb.append(result).append("\n");

                }
                Log.e("wxf", sb.toString());

                list.add("");
                adapter.setDataChange(list);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }




    public List<String> riskList;
    public List<String> attachList;

        public void obtainData(){


            NetManager.getInstance(getActivity()).GetRiskRepairRecordDetail(ZjApplication.dzgDetailDB.getInspectionID() + "", ZjApplication.dzgInspectItemDB.getInspectContentID() + "", new OnResponseListener<RecordDetail>() {
                @Override
                public void onComplete(boolean isOK, RecordDetail detail, int errorCode, String errorMsg) {


                    if (isOK) {

                        if (detail != null) {

                            des_et.setText(detail.getRiskDesc());
                            zg_et.setText(detail.getRepairDesc());
                            if (detail.getAttachUrlList() == null || detail.getAttachUrlList().size() == 0) {
                                uploadGridView.setVisibility(View.GONE);
                            }
                            riskList = detail.getRiskAttachUrlList();
                            wtAdapter.setDataChange(detail.getRiskAttachUrlList());
                            setListViewHeightBasedOnChildren(uploadGridView);
                            if (detail.getRiskAttachUrlList() == null || detail.getRiskAttachUrlList().size() == 0) {
                                uploadGridView2.setVisibility(View.GONE);
                            }
                            ZjApplication.auditLogList = detail.getAuditLog();
                            LogUtils.getInstance().error("log   size ===" + detail.getAuditLog().size());
                            attachList = detail.getAttachUrlList();
                            zgAdapter.setDataChange(detail.getAttachUrlList());
                            setListViewHeightBasedOnChildren(uploadGridView2);

                        }
                    } else {
                        Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onInternError(int errorCode, String errorMessage) {

                    Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();
                }
            });
        }


    public ProgressDialog dialog ;
    public void doRepair(int state){
        String uid = (String) SharedPreferencesUtil.getData(getActivity(),"uid","");

        JSONObject obj = new JSONObject();
        try {
            obj.put("UserID", uid);
            obj.put("InspectionID", ZjApplication.dzgDetailDB.getInspectionID() + "");
            obj.put("InspectTaskID", DshDetailEditActivity.task.getInspectTaskID()+"");
            obj.put("AuditDesc", yj_et.getText().toString());
            obj.put("AuditResult", state+"");
        }catch(Exception e){

        }

        dialog = DialogUtil.createProgressDialog(getActivity(),"提示","操作中...");
        String request = obj.toString();
        NetManager.getInstance(getActivity()).AuditRepairRecord(request, new OnResponseListener<List<JcxDB>>() {
            @Override
            public void onComplete(boolean isOK, List<JcxDB> result, int errorCode, String errorMsg) {

                dialog.dismiss();
                if (isOK) {
                    Toast.makeText(getActivity(), "成功", Toast.LENGTH_SHORT).show();
                    getActivity().finish();

                } else {
                    Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();

                }
                Intent intent = new Intent(getActivity(), DshListActivity.class);
                startActivity(intent);
                getActivity().finish();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

                Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public  void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        // 设置参数
        listView.setLayoutParams(params);
    }

}
